package model

import (
	"LterServer/util"
	"sort"
	"strings"
	"time"

	"gitee.com/konyshe/gogo"
)

type LterClientInfo struct {
	Addr           string `json:"addr"`
	IPRegion       string `json:"ip_region"`
	OnTime         string `json:"on_time"`
	LastUnixUpTime int64  `json:"last_unix_up_time"`
	PcapCount      int    `json:"pcap_count"`
}

var (
	plterClientInfoMap               map[string]*LterClientInfo
	snlastLterClientInfoMapCheckTime int64
)

func InitLterClient() {
	if plterClientInfoMap == nil {
		plterClientInfoMap = make(map[string]*LterClientInfo)
	}
}

func AddLterClientInfo(addr string, nowTime time.Time) {
	item, ok := plterClientInfoMap[addr]
	if ok {
		item.LastUnixUpTime = nowTime.Unix()

	} else {
		ip := strings.Split(addr, ":")[0]
		ipRegion, _ := util.GetIPRegion(ip)

		var sIpRegion string
		if ipRegion.Country != "0" {
			sIpRegion += ipRegion.Country
		}

		if ipRegion.Province != "0" {
			sIpRegion += ipRegion.Province
		}

		sIpRegion += ipRegion.City

		if ipRegion.City != ipRegion.ISP {
			sIpRegion += ipRegion.ISP
		}

		plterClientInfoMap[addr] = &LterClientInfo{
			addr,
			sIpRegion,
			nowTime.Format("2006-01-02 15:04:05"),
			nowTime.Unix(),
			0,
		}

		gogo.LogDebugF("Lter ON: %s", addr)
	}
}

func AddLterClientInfoPcapNum(addr string, num int, nowTime time.Time) {
	item, ok := plterClientInfoMap[addr]
	if ok {
		item.PcapCount += num
		item.LastUnixUpTime = nowTime.Unix()
	}
}

func UpLterClientInfo(info LterClientInfo) {
	item, ok := plterClientInfoMap[info.Addr]
	if ok {
		if info.IPRegion != "" {
			item.IPRegion = info.IPRegion
		}

		if info.OnTime != "" {
			item.OnTime = info.OnTime
		}

		if info.LastUnixUpTime != 0 {
			item.LastUnixUpTime = info.LastUnixUpTime
		}

		if info.PcapCount != 0 {
			item.PcapCount = info.PcapCount
		}
	}
}

func CheckLterClientInfoMap(nowUnixTime int64) {
	if plterClientInfoMap == nil {
		return
	}

	if nowUnixTime-snlastLterClientInfoMapCheckTime >= 5 {
		for addr := range plterClientInfoMap {
			if nowUnixTime-plterClientInfoMap[addr].LastUnixUpTime >= 20 {
				//lter := plterClientInfoMap[addr]
				//lter.PcapCount++
				//plterClientInfoMap[addr] = lter
				delete(plterClientInfoMap, addr)
				gogo.LogInfo("Check Lter OFF: " + addr)
			} else {
				//gogo.LogDebug("Check Lter ON: " + addr)
			}
		}

		snlastLterClientInfoMapCheckTime = nowUnixTime
	}
}

func GetLterClientInfoListJSON() []*LterClientInfo {
	sorted_keys := make([]string, 0)

	for k, _ := range plterClientInfoMap {
		sorted_keys = append(sorted_keys, k)
	}

	// sort 'string' key in increasing order
	sort.Strings(sorted_keys)

	var lterList []*LterClientInfo

	for _, k := range sorted_keys {
		lterList = append(lterList, plterClientInfoMap[k])
	}

	return lterList
}
